<template>
  <div style="height: 100%; background-color: #232733; border-radius: 10px;" ref="chart"></div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { map } from '@/utils/api';

const chart = ref(null);
let option = {
  legend: { // 图例配置
    data: ["黄金用户"],
    textStyle: {
      color: 'white' // 设置图例文字颜色为白色，以便在深色背景上显示
    }
  },
  geo: {
    map: 'china',
  },
  series: [
    {
      name: "黄金用户",
      type: "scatter",
      coordinateSystem: "geo",
      data: [
        {
          name: "武汉",
          value: [114.31, 30.52]
        }
      ]
    },
  ]
};

const initChart = async (mapData) => {
  await nextTick(); // 确保 DOM 已经更新
  if (!chart.value) {
    console.error('Chart container is not available');
    return;
  }

  echarts.registerMap('china', mapData);
  const myChart = echarts.init(chart.value);

  // 获取地图数据并更新 option
  map().then(res => {
    console.log(res);
    option.legend.data = res.map(item => item.name);
    option.series = res.map(item => ({
      name: item.name,
      type: "scatter",
      coordinateSystem: "geo",
      data: item.children
    }));

    // 更新图表配置
    myChart.setOption(option);
  }).catch(err => {
    console.error('Failed to load map data:', err);
  });

  // 初始化图表配置
  myChart.setOption(option);
};

onMounted(() => {
  fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
    .then(response => response.json())
    .then(res => {
      console.log(res);
      initChart(res);
    })
    .catch(err => {
      console.error('Failed to load map data:', err);
    });
});
</script>
